const initialState = { articleData: {} as ArticleMap, articleDetail: {} as ArticleDetail };
type ArticleMap = {
  [key: number]: ArticleData;
};
export default function articleReducer(state = initialState, action: any) {
  switch (action.type) {
    case 'article/setArticleData':
      // 1. 获取原有的数据  上拉加载更多数据进行合并
      const oldList = state.articleData[action.payload.channel_id]?.results || [];
      // 2. 获取新的数据
      const newList = action.payload.data.results;
      // 3. 合并数据
      const results = [...oldList, ...newList];

      return {
        ...state,
        articleData: {
          // 为了防止覆盖，需要先展开原有的数据
          ...state.articleData,
          // 存储键值对数据
          [action.payload.channel_id]: {
            ...action.payload.data,
            results,
          },
        },
      };
    // 下拉刷新
    case 'article/refresh':
      return {
        ...state,
        articleData: {
          ...state.articleData,
          [action.payload.channel_id]: action.payload.data,
        },
      };
    // 文章详情
    case 'article/setArticleDetail':
      return {
        ...state,
        articleDetail: action.payload,
      };
    default:
      return state;
  }
}
interface ArticleData {
  results: ArticleResult[];
  pre_timestamp: string;
}

export interface ArticleResult {
  art_id: string;
  title: string;
  aut_id: string;
  comm_count: number;
  pubdate: string;
  aut_name: string;
  is_top: number;
  cover: Cover;
}

interface Cover {
  type: number;
  images?: string[];
}
export interface ArticleDetail {
  art_id: string;
  title: string;
  pubdate: string;
  aut_id: string;
  content: string;
  aut_name: string;
  aut_photo: string;
  is_followed: boolean;
  is_collected: boolean;
  attitude: number;
  comm_count: number;
  read_count: number;
  like_count: number;
}
